package com.xianyu.myorder;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteConstraintException;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class OrderDao {
    private static final String TAG = "OrdersDao";
    public static final String TABLE_NAME = "Orders";

    // 列定义
    private final String[] ORDER_COLUMNS = new String[]{"Id", "OrderName", "OrderPrice", "OrderImage", "OrderType"};
    private final String[] DishName = new String[]{"OrderName"};
    private final String[] DishImage = new String[]{"OrderImage"};

    private final Context context;
    private final OrderDBHelper ordersDBHelper;

    public OrderDao(Context context) {
        this.context = context;
        ordersDBHelper = new OrderDBHelper(context);
    }

    /**
     * 判断表中是否有数据
     */
    public boolean isDataExist() {
        int count = 0;
        // select count(Id) from Orders
        try (SQLiteDatabase db = ordersDBHelper.getReadableDatabase(); Cursor cursor = db.query(OrderDBHelper.TABLE_NAME, new String[]{"COUNT(Id)"}, null, null, null, null, null)) {
            if (cursor.moveToFirst()) {
                count = cursor.getInt(0);
            }
            if (count > 0) return true;
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return false;
    }

    /**
     * 初始化数据
     */
    public void initTable() {
        SQLiteDatabase db = null;
        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();
            // insert into Orders(OrderName, OrderPrice, OrderImage, OrderType) values ("name", price, "image", type);
            db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (OrderName, OrderPrice, OrderImage, OrderType) values ('鱼香肉丝盖饭', 25, '', 3)");
            db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (OrderName, OrderPrice, OrderImage, OrderType) values ('爆炒腰花', 30, '', 4)");
            db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (OrderName, OrderPrice, OrderImage, OrderType) values ('卤鹅', 70, '', 6)");
            db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (OrderName, OrderPrice, OrderImage, OrderType) values ('凉拌豆腐', 15, '', 1)");
            db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (OrderName, OrderPrice, OrderImage, OrderType) values ('汉堡包', 8, '', 2)");
            db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (OrderName, OrderPrice, OrderImage, OrderType) values ('三明治', 6, '', 2)");
            db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (OrderName, OrderPrice, OrderImage, OrderType) values ('油条', 4, '', 2)");
            db.execSQL("insert into " + OrderDBHelper.TABLE_NAME + " (OrderName, OrderPrice, OrderImage, OrderType) values ('牛排', 40, '', 7)");
            db.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e(TAG, "", e);
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
    }

    /**
     * 查询数据库中所有数据
     */
    public List<Order> getAllDate() {
        // select * from Orders
        try (SQLiteDatabase db = ordersDBHelper.getReadableDatabase(); Cursor cursor = db.query(OrderDBHelper.TABLE_NAME, ORDER_COLUMNS, null, null, null, null, null)) {
            if (cursor.getCount() > 0) {
                List<Order> orderList = new ArrayList<>(cursor.getCount());
                while (cursor.moveToNext()) {
                    orderList.add(parseOrder(cursor));
                }
                return orderList;
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return null;
    }

    /**
     * 查询所有菜名
     */
    public List<String> getAllDishName() {
        // select OrderName from Orders
        try (SQLiteDatabase db = ordersDBHelper.getReadableDatabase(); Cursor cursor = db.query(OrderDBHelper.TABLE_NAME, DishName, null, null, null, null, null)) {
            if (cursor.getCount() > 0) {
                List<String> list = new ArrayList<>(cursor.getCount());
                while (cursor.moveToNext()) {
                    list.add(cursor.getString(cursor.getColumnIndex("OrderName")));
                }
                return list;
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return null;
    }

    /**
     * 根据菜名查询图片
     */
    public List<String> getImageByDishName(String name) {
        // select OrderImage from Orders where OrderName = ?
        try (SQLiteDatabase db = ordersDBHelper.getReadableDatabase(); Cursor cursor = db.query(OrderDBHelper.TABLE_NAME, DishImage, "OrderName = ?", new String[]{name}, null, null, null)) {
            if (cursor.getCount() > 0) {
                List<String> list = new ArrayList<>(cursor.getCount());
                while (cursor.moveToNext()) {
                    list.add(cursor.getString(cursor.getColumnIndex("OrderImage")));
                }
                return list;
            } else Toast.makeText(context, "找不到该图片", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return null;
    }

    /**
     * 根据id和name判断数据库是否有id不相同但是name相同的数据
     */
    public Boolean getDataByIdAndDishName(int id, String name) {
        // select * from Orders where OrderName = ? AND OrderID != ?
        try (SQLiteDatabase db = ordersDBHelper.getReadableDatabase(); Cursor cursor = db.query(OrderDBHelper.TABLE_NAME, ORDER_COLUMNS, "OrderName = ? AND Id != ?", new String[]{name, String.valueOf(id)}, null, null, null)) {
            if (cursor.getCount() > 0) {
                return true;
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return false;
    }

    /**
     * 新增一条数据
     */
    public boolean insertDate(String name, int price, String image, int type) {
        SQLiteDatabase db = null;
        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();
            // insert into Orders(OrderName, OrderPrice, OrderImage, OrderType) values ("name", price, "image", type);
            ContentValues contentValues = new ContentValues();
            contentValues.put("OrderName", name);
            contentValues.put("OrderPrice", price);
            contentValues.put("OrderImage", image);
            contentValues.put("OrderType", type);
            db.insertOrThrow(OrderDBHelper.TABLE_NAME, null, contentValues);
            db.setTransactionSuccessful();
            return true;
        } catch (SQLiteConstraintException e) {
            Toast.makeText(context, "主键重复", Toast.LENGTH_SHORT).show();
        } catch (Exception e) {
            Log.e(TAG, "", e);
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return false;
    }

    /**
     * 删除一条数据  根据id删除
     */
    public boolean deleteOrder(int id) {
        SQLiteDatabase db = null;
        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();
            // delete from Orders where Id = ?
            db.delete(OrderDBHelper.TABLE_NAME, "Id = ?", new String[]{String.valueOf(id)});
            db.setTransactionSuccessful();
            return true;
        } catch (Exception e) {
            Log.e(TAG, "", e);
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return false;
    }

    /**
     * 修改一条数据  将Id为?的数据修改
     */
    public boolean updateOrder(int id, String name, int price, String image, int type) {
        SQLiteDatabase db = null;
        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();
            // update Orders set OrderName = ?, OrderPrice = ?, OrderImage = ?, OrderType = ? where Id = ?
            ContentValues cv = new ContentValues();
            cv.put("OrderName", name);
            cv.put("OrderPrice", price);
            cv.put("OrderImage", image);
            cv.put("OrderType", type);
            db.update(OrderDBHelper.TABLE_NAME,
                    cv,
                    "Id = ?",
                    new String[]{String.valueOf(id)});
            db.setTransactionSuccessful();
            return true;
        } catch (Exception e) {
            Log.e(TAG, "", e);
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
        return false;
    }

    /**
     * 模糊查询  此处将菜名为?的信息提取出来
     */
    public List<Order> getOrderByNameLike(String name) {
        // select * from Orders where OrderName LIKE '%'?'%'
        try (SQLiteDatabase db = ordersDBHelper.getReadableDatabase(); Cursor cursor = db.query(OrderDBHelper.TABLE_NAME,
                ORDER_COLUMNS,
                "OrderName LIKE ?",
                new String[]{"%" + name + "%"},
                null, null, null)) {
            if (cursor.getCount() > 0) {
                List<Order> orderList = new ArrayList<>(cursor.getCount());
                while (cursor.moveToNext()) {
                    Order order = parseOrder(cursor);
                    orderList.add(order);
                }
                return orderList;
            } else {
                Toast.makeText(context, "找不到相关信息，请检查输入信息是否正确", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return null;
    }

    /**
     * 匹配查询  此处将菜名为?的信息提取出来
     */
    public List<Order> getOrderByName(String name) {
        // select * from Orders where OrderName = ?
        try (SQLiteDatabase db = ordersDBHelper.getReadableDatabase(); Cursor cursor = db.query(OrderDBHelper.TABLE_NAME,
                ORDER_COLUMNS,
                "OrderName = ?",
                new String[]{name},
                null, null, null)) {
            if (cursor.getCount() > 0) {
                List<Order> orderList = new ArrayList<>(cursor.getCount());
                while (cursor.moveToNext()) {
                    Order order = parseOrder(cursor);
                    orderList.add(order);
                }
                return orderList;
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return null;
    }

    /**
     * 数据查询  此处将类型为?的信息提取出来
     */
    public List<Order> getOrderByType(int type) {
        // select * from Orders where OrderType = ?
        try (SQLiteDatabase db = ordersDBHelper.getReadableDatabase(); Cursor cursor = db.query(OrderDBHelper.TABLE_NAME,
                ORDER_COLUMNS,
                "OrderType = ?",
                new String[]{type + ""},
                null, null, null)) {
            if (cursor.getCount() > 0) {
                List<Order> orderList = new ArrayList<>(cursor.getCount());
                while (cursor.moveToNext()) {
                    Order order = parseOrder(cursor);
                    orderList.add(order);
                }
                return orderList;
            } else {
                Toast.makeText(context, "找不到相关信息，请检查输入信息是否正确", Toast.LENGTH_SHORT).show();
            }
        } catch (Exception e) {
            Log.e(TAG, "", e);
        }
        return null;
    }

    /**
     * 将查找到的数据转换成Order类
     */
    private Order parseOrder(Cursor cursor) {
        int id = cursor.getInt(cursor.getColumnIndex("Id"));
        String name = cursor.getString(cursor.getColumnIndex("OrderName"));
        int price = cursor.getInt(cursor.getColumnIndex("OrderPrice"));
        String image = cursor.getString(cursor.getColumnIndex("OrderImage"));
        int type = cursor.getInt(cursor.getColumnIndex("OrderType"));
        return new Order(id, name, price, image, type);
    }

    /**
     * 删除数据库表
     */
    public void dropDB() {
        SQLiteDatabase db = null;
        try {
            db = ordersDBHelper.getWritableDatabase();
            db.beginTransaction();
            // delete Orders
            db.delete(TABLE_NAME, null, null);
            db.setTransactionSuccessful();
        } catch (Exception e) {
            Log.e(TAG, "", e);
        } finally {
            if (db != null) {
                db.endTransaction();
                db.close();
            }
        }
    }
}
